package cn.txun.springboot62.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class UploadController {
    @RequestMapping("/upload")
    public String upload(MultipartFile picFile) throws IOException {
        String filename = picFile.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID()+suffix;
        //准备文件夹路径
        String dirPath = "d:/upload";
        //准备一个和日期相关的路径  yyyy/MM/dd
        SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
        //new Date()得到当前系统时间
        String dataPath = f.format(new Date());
        // d:/upload/2023/12/7
        File dirFile = new File(dirPath + dataPath);
        //如果文件夹不存在，则创建
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //把图片保存到上面的文件夹中
        picFile.transferTo(new File(dirFile,filename));
        //服务端完成上传图片后，将图片路径响应给客户端
                // /2023/12/07/xxxx.jpg
        return dataPath+filename ;
    }

    @RequestMapping("/remove")
    public void remove(String url){
        System.out.println(url);
        new File("d:/upload"+url).delete();
    }
}
